package com.wh.custom.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wh.basic.utils.TimeUtil;
import com.wh.basic.utils.ExcelUtils;
import com.wh.basic.vo.AjaxResult;
import com.wh.custom.dao.*;
import com.wh.custom.dto.CustomAddValidationDto;
import com.wh.custom.dto.CustomSearchDto;
import com.wh.custom.mapper.CustomReturnVisitMapper;
import com.wh.custom.pojo.Allocation;
import com.wh.custom.pojo.CustomReturnVisit;
import com.wh.custom.pojo.CustomTemplate;
import com.wh.custom.vo.CustomExport;
import com.wh.custom.vo.CustomExportDto;
import com.wh.custom.vo.CustomExportVo;
import com.wh.custom.vo.CustomRecordVo;
import com.wh.order.pojo.OrderList;
import com.wh.org.dao.IEmployeeDao;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.wh.custom.pojo.CustomMycustom;
import com.wh.custom.service.ICustomMycustomService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wh.custom.dto.CustomMycustomQueryDto;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 业务实现类
 */
@Service
public class CustomMycustomServiceImpl extends ServiceImpl<CustomMycustomMapper, CustomMycustom> implements ICustomMycustomService {

    @Autowired
    private CustomMycustomMapper customMycustomMapper;


    @Autowired
    public CustomTypeMapper customTypeMapper;
    @Autowired
    public CustomLabelMapper customLabelMapper;
    @Autowired
    public CustomSourceMapper customSourceMapper;
    @Autowired
    public CustomSalesmanMapper customSalesmanMapper;
    @Autowired
    private IEmployeeDao iEmployeeDao;
    @Autowired
    private CustomReturnVisitMapper customReturnVisitMapper;

    @Transactional
    @Override
    public IPage<CustomMycustom> findByPage(CustomMycustomQueryDto customMycustomQueryDto) {
        IPage<CustomMycustom> page = new Page<>(customMycustomQueryDto.getCurrentPage(), customMycustomQueryDto.getPageSize());
        QueryWrapper<CustomMycustom> qw = new QueryWrapper<>();

        qw.like("company_name", customMycustomQueryDto.getKeyword());
        qw.or();
        qw.like("customer_name", customMycustomQueryDto.getKeyword());
        page.setRecords(customMycustomMapper.findByPage(page, qw));
        page.setTotal(customMycustomMapper.selectCount(qw));

        return page;
    }
    //分配客户
    @Override
    public void allocation(Allocation allocation) {
        List<Long> ids = allocation.getIds();
        Long salesmanId = allocation.getSalesmanId();
        for (Long id : ids) {
            customMycustomMapper.allocation(id, salesmanId);
        }
    }

    /**
     * 多条件查询——公共代码块
     * @param customSearchDto
     * @param qw
     */
    private void processCustomSearchDto(CustomSearchDto customSearchDto, QueryWrapper<CustomMycustom> qw) {
        ArrayList<String> labelList = new ArrayList<>();
        ArrayList<String> sourceList = new ArrayList<>();
        ArrayList<String> typeList = new ArrayList<>();

        String customerLabelId = customSearchDto.getCustomerLabelId();
        processListString(customerLabelId, labelList);

        String customerSourceId = customSearchDto.getCustomerSourceId();
        processListString(customerSourceId, sourceList);

        String customerTypeId = customSearchDto.getCustomerTypeId();
        processListString(customerTypeId, typeList);

        Long phone = customSearchDto.getPhone();
        Long salesmanId = customSearchDto.getSalesmanId();
        String time = customSearchDto.getTime();
        String customerName = customSearchDto.getCustomerName();
        String[] timelist = null;
        if (!time.isEmpty()) {
            timelist = time.split(",");
        }

        if (!labelList.isEmpty()) {
            qw.in("label_id", labelList);
        }
        if (!sourceList.isEmpty()) {
            qw.in("source_id", sourceList);
        }
        if (!typeList.isEmpty()) {
            qw.in("type_id", typeList);
        }
        if (timelist != null) {
            qw.between("last_deal_time", timelist[0], timelist[1]);
        }
        if (phone != null) {
            qw.like("phone_number", phone);
        }

        if (!com.wh.basic.vo.StringUtils.isEmpty(customerName)) {
            qw.like("customer_name", customerName);
        }
    }

    private void processListString(String inputString, List<String> outputList) {
        if (!inputString.isEmpty()) {
            String[] items = inputString.split(",");
            outputList.addAll(Arrays.asList(items));
        }
    }





    /**
     * 客户列表——多条件查询
     * @param customSearchDto
     * @return
     */
    @Override
    public IPage<CustomMycustom> getAaaa(CustomSearchDto customSearchDto) {
        IPage<CustomMycustom> page = new Page<>(customSearchDto.getCurrentPage(), customSearchDto.getPageSize());
        QueryWrapper<CustomMycustom> qw = new QueryWrapper<>();
        processCustomSearchDto(customSearchDto, qw);
        Long salesmanId = customSearchDto.getSalesmanId();
        if (salesmanId != null) {
            qw.eq("salesman_id", salesmanId);
        }
        qw.orderByAsc("case when is_top = 1 then 0 else 1 end");
        qw.orderByDesc("update_time");
        page.setRecords(customMycustomMapper.findByPage(page, qw));
        page.setTotal(customMycustomMapper.selectCount(qw));
        return page;
    }

    /**
     * 公海客户——多条件查询
     * @param customSearchDto
     * @return
     */
    @Override
    public IPage<CustomMycustom> getHighSeas(CustomSearchDto customSearchDto) {
        IPage<CustomMycustom> page = new Page<>(customSearchDto.getCurrentPage(), customSearchDto.getPageSize());
        QueryWrapper<CustomMycustom> qw = new QueryWrapper<>();
        qw.isNull("salesman_id");
        qw.orderByDesc("update_time");
        processCustomSearchDto(customSearchDto, qw);
        page.setRecords(customMycustomMapper.findByPage(page, qw));
        page.setTotal(customMycustomMapper.selectCount(qw));
        return page;
    }

    /**
     * 我的客户——多条件查询
     * @param customSearchDto
     * @return
     */
    @Override
    public IPage<CustomMycustom> getMyCustom(CustomSearchDto customSearchDto) {
        IPage<CustomMycustom> page = new Page<>(customSearchDto.getCurrentPage(), customSearchDto.getPageSize());
        QueryWrapper<CustomMycustom> qw = new QueryWrapper<>();
        Long loginid = customSearchDto.getLoginId();
        Long salesmanId = iEmployeeDao.findEmployeeIdByloginId(loginid);
        qw.eq("salesman_id", salesmanId);
        qw.orderByAsc("case when personal_top = 1 then 0 else 1 end");
        qw.orderByDesc("update_time");
        processCustomSearchDto(customSearchDto, qw);
        page.setRecords(customMycustomMapper.findByPage(page, qw));
        page.setTotal(customMycustomMapper.selectCount(qw));
        return page;
    }

    /**
     * 通过手机号查询是否存在客户
     * @param phoneNumber
     * @return
     */
    @Override
    public Long checkCustomer(String phoneNumber) {
        Long idByphoneNumber = customMycustomMapper.findIdByphoneNumber(phoneNumber);
        return  idByphoneNumber;
    }

    /**
     * 添加客户信息
     * 返回新增的客户id
     *
     * @param customMycustom
     * @return
     */
    @Override
    @Transactional
    public Integer addOrderCustomer(CustomMycustom customMycustom) {
        //1获取当前登录人id，新建一位客户
        Integer salesmanId = customMycustom.getSalesmanId();
        Long saleamanId = new Long(salesmanId);
        Integer idbyLogininfoId = iEmployeeDao.findIdbyLogininfoID(saleamanId);
        customMycustom.setUpdateTime(LocalDateTime.now());
        customMycustom.setEntryCustomerTime(LocalDateTime.now());
        customMycustom.setSalesmanId(idbyLogininfoId);
        customMycustomMapper.insert(customMycustom);
        //获取新增客户id
        Integer id = customMycustom.getId();
        //2同时插入一条新建数据 在回访表
        CustomReturnVisit customReturnVisit = new CustomReturnVisit();

        //TODO 客户列表按照这个时间倒叙
        customReturnVisit.setDate(LocalDateTime.now());
        //填写新增客户id
        customReturnVisit.setCustomId(new Long(id));
        //填写操作人id
        customReturnVisit.setOperator(saleamanId);
        customReturnVisit.setRecordType(0);
        customReturnVisit.setContent("通过订单创建客户：客户id：" + id);
        customReturnVisitMapper.insert(customReturnVisit);
        return customMycustom.getId();
    }

    /**
     * 添加客户，非公海客户
     * @param customMycustom
     */
    @Override
    @Transactional
    public void AddMycustom(CustomMycustom customMycustom) {
        Integer salesmanId = customMycustom.getSalesmanId();
        customMycustom.setUpdateTime(LocalDateTime.now());
        Long saleamanId=new Long(salesmanId);
        Integer idbyLogininfoId = iEmployeeDao.findIdbyLogininfoID(saleamanId);
        customMycustom.setSalesmanId(idbyLogininfoId);
        customMycustomMapper.insert(customMycustom);
        //获取新增客户id
        Integer id = customMycustom.getId();
        //2同时插入一条新建数据 在回访表
        CustomReturnVisit customReturnVisit = new CustomReturnVisit();

        //TODO 客户列表按照这个时间倒叙
        customReturnVisit.setDate(LocalDateTime.now());
        //填写新增客户id
        customReturnVisit.setCustomId(new Long(id));
        //填写操作人id
        customReturnVisit.setOperator(new Long(idbyLogininfoId));
        customReturnVisit.setRecordType(0);
        customReturnVisit.setContent("创建自己的客户：客户id：" + id);
        customReturnVisitMapper.insert(customReturnVisit);
    }
    //客户信息更改
    @Override
    @Transactional

    public void updateCustomer(CustomMycustom customMycustom) {
        //当前登录人id
        Long loginId = customMycustom.getLoginId();
        //最后处理时间为当前时间
        customMycustom.setUpdateTime(LocalDateTime.now());

        Long idbyLogininfoId = iEmployeeDao.findIdbyLogininfoId(loginId);
        // 根据ID获取旧数据
        CustomMycustom oldMyCustomer = customMycustomMapper.selectById(customMycustom.getId());


        // 落库更新数据
        customMycustomMapper.updateById(customMycustom);
        CustomMycustom newCustomer = customMycustomMapper.selectById(customMycustom.getId());

        // 记录下旧数据的副本
        CustomMycustom oldCustomerCopy = new CustomMycustom();
        //将旧数据赋值给一个对象
        BeanUtils.copyProperties(oldMyCustomer, oldCustomerCopy);
        // 对比旧数据与新修改数据，记录更改信息
        StringBuilder s = new StringBuilder();
        compareAndAppend(s, "客户名", newCustomer.getCustomerName(), oldCustomerCopy.getCustomerName());
        compareAndAppend(s, "手机号", newCustomer.getPhoneNumber(), oldCustomerCopy.getPhoneNumber());
        compareAndAppend(s, "公司名", newCustomer.getCompanyName(), oldCustomerCopy.getCompanyName());
        compareAndAppend(s, "详细地址", newCustomer.getAddress(), oldCustomerCopy.getAddress());
        compareAndAppend(s, "所属地区", newCustomer.getArea(), oldCustomerCopy.getArea());
        compareAndAppend(s, "备注", newCustomer.getNotes(), oldCustomerCopy.getNotes());
        compareAndAppend(s, "客户级别", customLabelMapper.selectByIdname(newCustomer.getLabelId()), customLabelMapper.selectByIdname(oldCustomerCopy.getLabelId()));
        compareAndAppend(s, "客户来源", customSourceMapper.selectByIdname(newCustomer.getSourceId()), customSourceMapper.selectByIdname(oldCustomerCopy.getSourceId()));
        compareAndAppend(s, "客户销售渠道", customTypeMapper.selectByIdname(newCustomer.getTypeId()), customTypeMapper.selectByIdname(oldCustomerCopy.getTypeId()));

        // 如果有更改记录，则保存到CustomReturnVisit表中
        if (s.length() > 0) {
            CustomReturnVisit customReturnVisit = new CustomReturnVisit();
            customReturnVisit.setDate(LocalDateTime.now());
            customReturnVisit.setCustomId(new Long(customMycustom.getId()));
            customReturnVisit.setOperator(idbyLogininfoId);
            customReturnVisit.setRecordType(0);
            customReturnVisit.setContent(s.toString());
            customReturnVisitMapper.insert(customReturnVisit);
        }
    }
    private void compareAndAppend(StringBuilder s, String fieldName, Object newValue, Object oldValue) {
        if (newValue != null && !newValue.equals(oldValue)) {
            s.append("修改了").append(fieldName).append("为：").append(newValue).append("\n");
        }
    }


            /**
             * 回收公海
             * @param ids
             */
    @Override
    public void recovery(List<Long> ids) {
        for (Long id : ids) {
            customMycustomMapper.recovery(id);
        }
    }

    @Override
    public void export(HttpServletResponse response) {
        List<CustomMycustom> mycustoms = customMycustomMapper.selectList(null);
        //将关联表数据填充上去
        for (CustomMycustom mycustom : mycustoms) {
            mycustom.setTypes(customTypeMapper.selectByIdname(mycustom.getTypeId()));
            mycustom.setLabels(customLabelMapper.selectByIdname(mycustom.getLabelId()));
            mycustom.setSources(customSourceMapper.selectByIdname(mycustom.getSourceId()));
            mycustom.setSalesmans(iEmployeeDao.selectByIdname(mycustom.getSalesmanId()));
        }
        //ExcelUtils.exportExcel(导出的数据, 标题, 页名称, 导出的类型, 文件名, 响应对象)
        //文件名如果不写后缀默认是xls，可以写上xlsx就是指定的xlsx类型
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY_MM_dd");
        String time = dateFormat.format(new Date());
        ExcelUtils.exportExcel(mycustoms, "客户信息表", "客户信息", CustomMycustom.class, "客户信息表" + time + ".xls", response);
    }

    /**
     * 导出模板
     * @param response
     */
    public void exportTemplate(HttpServletResponse response) {
        // 创建一个空的数据列表，不包含实际数据
        List<CustomTemplate> emptyList = new ArrayList<>();

        try {
            // 设置导出参数，只导出列名
            ExportParams exportParams = new ExportParams("客户信息表", "客户信息");

            // 生成 Excel 工作簿
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, CustomTemplate.class, emptyList);

            // 设置文件名
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd");
            String time = dateFormat.format(new Date());
            String fileName = "mu'ban" + time + ".xls";

            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 获取响应输出流
            OutputStream out = response.getOutputStream();

            // 将工作簿写入输出流
            workbook.write(out);

            // 关闭输出流
            out.close();

        } catch (IOException e) {
            e.printStackTrace();
            // 处理异常，例如记录日志或返回错误信息
        }
    }

    /**
     * 我的客户数据导出
     * @param LoginId
     * @param response
     */
    @Override
    public void mycustomerexport(Long LoginId,HttpServletResponse response) {
        Long salesmanId= iEmployeeDao.findEmployeeIdByloginId(LoginId);
        List<CustomMycustom> mycustoms = customMycustomMapper.selectmycustomer(salesmanId);
        String salesmanName = iEmployeeDao.selectByIdname(Math.toIntExact(salesmanId));
        //将关联表数据填充上去
        for (CustomMycustom mycustom : mycustoms) {
            mycustom.setTypes(customTypeMapper.selectByIdname(mycustom.getTypeId()));
            mycustom.setLabels(customLabelMapper.selectByIdname(mycustom.getLabelId()));
            mycustom.setSources(customSourceMapper.selectByIdname(mycustom.getSourceId()));
            String salesman = iEmployeeDao.selectByIdname(mycustom.getSalesmanId());
            mycustom.setSalesmans(salesman);
        }
        //ExcelUtils.exportExcel(导出的数据, 标题, 页名称, 导出的类型, 文件名, 响应对象)
        //文件名如果不写后缀默认是xls，可以写上xlsx就是指定的xlsx类型
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY_MM_dd");
        String time = dateFormat.format(new Date());
        ExcelUtils.exportExcel(mycustoms, "客户信息表", "客户信息", CustomMycustom.class, salesmanName+"的客户信息表" + time + ".xls", response);
    }

    @Override
    public AjaxResult importExcel(MultipartFile file) {
        List<CustomMycustom> skippedData = new ArrayList<>();//用于记录重复的数据
        List<CustomMycustom> typeerr = new ArrayList<>();//用于记录错误的数据
        List<String> errorMessages = new ArrayList<>();       // 用于记录错误信息
        List<CustomMycustom> list = ExcelUtils.importExcel(file, 1, 1, CustomMycustom.class);
        for (CustomMycustom mycustom : list) {
            //根据手机号判断是否重复
            String phoneNumber = mycustom.getPhoneNumber();
            if (phoneNumber.equals(customMycustomMapper.findphone(mycustom.getPhoneNumber()))) {
                //如果手机号重复，说明该客户已存在,则该条数据不存入,并记录下来
                skippedData.add(mycustom);
                continue;//跳出循环，执行下一次循环
            }
            String selectname = customSalesmanMapper.selectname(mycustom.getSalesmans());
            String selectname1 = customTypeMapper.selectname(mycustom.getTypes());
            String selectname2 = customLabelMapper.selectname(mycustom.getLabels());
            String selectname3 = customSourceMapper.selectname(mycustom.getSources());
            if (StringUtils.isBlank(selectname) || StringUtils.isBlank(selectname1) || StringUtils.isBlank(selectname2) || StringUtils.isBlank(selectname3)) {
                typeerr.add(mycustom);//记录数据
                errorMessages.add("数据类型不对，请检查后重新输入");
                //是错误表明输入的类型，来源，客户名，或者业务员输入的不正确
            } else {
                Integer salesmanId = customSalesmanMapper.selectId(mycustom.getSalesmans());
                Integer typeId = customTypeMapper.selectId(mycustom.getTypes());
                Integer labelId = customLabelMapper.selectId(mycustom.getLabels());
                Integer sourceId = customSourceMapper.selectId(mycustom.getSources());
                mycustom.setLabelId(labelId);
                mycustom.setTypeId(typeId);
                mycustom.setSourceId(sourceId);
                mycustom.setSalesmanId(salesmanId);
                customMycustomMapper.insert(mycustom);
            }

        }
        // 在方法最后判断是否有错误信息，如果有，返回错误信息
        if (!errorMessages.isEmpty()) {
            return AjaxResult.me().setSuccess(false).setMessage(String.join("\n", errorMessages));
        }

        // 返回重复的数据和错误的类型数据
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("skippedData", skippedData);
        resultMap.put("typeerr", typeerr);

        return AjaxResult.me().setResultObj(resultMap);
    }

    @Override
    //分类查询
    public IPage<CustomMycustom> sort(CustomMycustomQueryDto customMycustomQueryDto) {
        String queryMethod = customMycustomQueryDto.getSearchField();
        List<Integer> keywords = customMycustomQueryDto.getKeywords();
        IPage<CustomMycustom> page = new Page<>(customMycustomQueryDto.getCurrentPage(), customMycustomQueryDto.getPageSize());
        List<CustomMycustom> allResults = new ArrayList<>();
        QueryWrapper<CustomMycustom> qw = new QueryWrapper<>();
        for (Object id : keywords) {
            // 清空之前的查询条件
            qw.clear();
            // 根据不同的分类条件构建查询
            if ("type".equals(queryMethod)) {
                Integer typeId = (Integer) id;
                qw.eq("type_id", typeId);
            } else if ("source".equals(queryMethod)) {
                Integer sourceId = (Integer) id;
                qw.eq("source_id", sourceId);
            } else if ("label".equals(queryMethod)) {
                Integer labelId = (Integer) id;
                qw.eq("label_id", labelId);
            }
            // 执行查询，并将结果添加到集合中
            List<CustomMycustom> partialResults = customMycustomMapper.findByPage(page, qw);
            allResults.addAll(partialResults);
        }
        // 设置总记录数
        page.setTotal(allResults.size());
        // 将所有结果设置到分页对象中
        page.setRecords(allResults);
        // 返回分页对象
        return page;
    }
    //公海客户分类查询
    @Override
    public IPage<CustomMycustom> HighSeasSort(CustomMycustomQueryDto customMycustomQueryDto) {
        String queryMethod = customMycustomQueryDto.getSearchField();
        List<Integer> keywords = customMycustomQueryDto.getKeywords();
        IPage<CustomMycustom> page = new Page<>(customMycustomQueryDto.getCurrentPage(), customMycustomQueryDto.getPageSize());
        List<CustomMycustom> allResults = new ArrayList<>();
        QueryWrapper<CustomMycustom> qw = new QueryWrapper<>();
        qw.isNull("salesman_id");
        for (Object id : keywords) {
            // 清空之前的查询条件
            qw.clear();
            qw.isNull("salesman_id");
            // 根据不同的分类条件构建查询
            if ("type".equals(queryMethod)) {
                Integer typeId = (Integer) id;
                qw.eq("type_id", typeId);
            } else if ("source".equals(queryMethod)) {
                Integer sourceId = (Integer) id;
                qw.eq("source_id", sourceId);
            } else if ("label".equals(queryMethod)) {
                Integer labelId = (Integer) id;
                qw.eq("label_id", labelId);
            }
            // 执行查询，并将结果添加到集合中
            List<CustomMycustom> partialResults = customMycustomMapper.findByPage(page, qw);
            allResults.addAll(partialResults);
        }
        // 设置总记录数
        page.setTotal(allResults.size());
        // 将所有结果设置到分页对象中
        page.setRecords(allResults);
        // 返回分页对象
        return page;
    }

    @Override
    public Integer allNum() {
        Integer integer = customMycustomMapper.selectCount(null);

        return integer;
    }


    /**
     * 查询所有客户
     * @param customMycustomQueryDto
     * @return
     */
    @Override
    public IPage<CustomMycustom> all(CustomMycustomQueryDto customMycustomQueryDto) {
        IPage<CustomMycustom> page = new Page<>(customMycustomQueryDto.getCurrentPage(), customMycustomQueryDto.getPageSize());
        QueryWrapper<CustomMycustom> qw = new QueryWrapper<>();
        page.setRecords(customMycustomMapper.findByPage(page, qw));
        page.setTotal(customMycustomMapper.selectCount(qw));
        return page;
    }

    /**
     * 查询公海客户
     * @param customMycustomQueryDto
     * @return
     */
    @Override
    public IPage<CustomMycustom> findhighSeas(CustomMycustomQueryDto customMycustomQueryDto) {
        IPage<CustomMycustom> page = new Page<>(customMycustomQueryDto.getCurrentPage(), customMycustomQueryDto.getPageSize());
        QueryWrapper<CustomMycustom> qw = new QueryWrapper<>();

        qw.isNull("salesman_id")
                .and(wrapper -> wrapper.like("company_name", customMycustomQueryDto.getKeyword())
                        .or()
                        .like("customer_name", customMycustomQueryDto.getKeyword()));

        page.setRecords(customMycustomMapper.findByPage(page, qw));
        page.setTotal(customMycustomMapper.selectCount(qw));

        return page;
    }

    /**
     * 查询当前登陆人的客户
     * @param customMycustomQueryDto
     * @return
     */
    @Override
    public IPage<CustomMycustom> mycustomer(CustomMycustomQueryDto customMycustomQueryDto) {
        Long loginid = customMycustomQueryDto.getLoginId();
        Long salesmanId= iEmployeeDao.findEmployeeIdByloginId(loginid);
        IPage<CustomMycustom> page = new Page<>(customMycustomQueryDto.getCurrentPage(), customMycustomQueryDto.getPageSize());
        QueryWrapper<CustomMycustom> qw = new QueryWrapper<>();

        qw.eq("salesman_id",salesmanId)
                .and(wrapper -> wrapper.like("company_name", customMycustomQueryDto.getKeyword())
                        .or()
                        .like("customer_name", customMycustomQueryDto.getKeyword()));

        page.setRecords(customMycustomMapper.findByPage(page, qw));
        page.setTotal(customMycustomMapper.selectCount(qw));

        return page;
    }

    /**
     * 录入新客户 的 校验 ，可以录入返回true，反之false
     * @param customAddValidationDto
     * @return
     */
    @Override
    public Map<String,Object> phoneValidation(CustomAddValidationDto customAddValidationDto) {
        HashMap<String, Object> result = new HashMap<>();
        //1获取参数内容
        String phone = customAddValidationDto.getPhone();
        String companyName = customAddValidationDto.getCompanyName();
        //查询手机号
        Long idByphoneNumber = customMycustomMapper.findIdByphoneNumber(phone);
        //查到手机号重复
        if(idByphoneNumber != null){
            //查询手机号和公司名称是否符合
            Long boole = customMycustomMapper.phoneValidation(phone,companyName);
            if(boole !=null){
                // 返回了客户id，说明数据重复，返回true, 表示数据重复,不可以录入
                result.put("customerId", boole);
                result.put("canAdd", true);
            } else {
                // 手机号重复但公司名称不符合，可以录入
                result.put("customerId", null);
                result.put("canAdd", false);
            }
        }
        return result;
    }


    @Override
    public void addCustomer( CustomMycustom customMycustom,Long LoginId) {
        CustomReturnVisit customReturnVisit = new CustomReturnVisit();
        //1客户数据落库，
        customMycustomMapper.insert(customMycustom);
        //获取新增客户id
        Integer id = customMycustom.getId();
        //2添加活跃记录
        customReturnVisit.setCustomId(new Long(id));
        //TODO 客户列表按照这个时间倒叙
        customReturnVisit.setDate(LocalDateTime.now());
        //TODO  获取当前登陆人id
        //当前登陆人的id
        Long loginId = iEmployeeDao.findEmployeeIdByloginId(LoginId);
        customReturnVisit.setOperator(loginId);
        customReturnVisit.setRecordType(0);
        customReturnVisit.setContent("创建客户：客户id：" + id);
        customReturnVisitMapper.insert(customReturnVisit);
    }

    @Override
    public CustomExport exportSSL(List<CustomExportDto> exportDtos, String[] idArr) {
        if (!ObjectUtils.isEmpty(exportDtos)) {
            String[] props = new String[exportDtos.size() + 1];
            String[] labels = new String[exportDtos.size() + 1];
            for (int i = 0; i < exportDtos.size(); i++) {
                CustomExportDto customExportDto = exportDtos.get(i);
                if (customExportDto.getChecked()) {
                    props[i] = customExportDto.getProp();
                    labels[i] = customExportDto.getLabel();
                }
            }
            //根据订单编号查询出所有订单数据
            List<CustomExportVo> exportVos = customMycustomMapper.findAllExportOrder(idArr);
            CustomExport customExport = new CustomExport();
            customExport.setLabels(labels);
            customExport.setProps(props);
            customExport.setExportVos(exportVos);
            return customExport;
        }
        return null;
    }

    @Override
    public List<CustomRecordVo> getOrderMessageByOrderSn(String orderSn) {
        return null;
    }



    @Override
    public Map<String, Object> getCustomDataCount(String type) {
        Map<String, Object> maps = new HashMap<>();
        if ("year".equals(type)) {
            List<Integer> counts = new ArrayList<>();
            LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
            List<String> nowYearMonth = TimeUtil.getNowYearMonth();
            maps.put("subscript", nowYearMonth);
            for (String yearMonth : nowYearMonth) {
                map.put(yearMonth, 0);
            }
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy");
            String year = currentDate.format(formatter);
            List<CustomMycustom> customMycustoms = customMycustomMapper.getCustomDataByNowYear(year);
            if (!ObjectUtils.isEmpty(customMycustoms)) {
                DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy-MM");
                for (CustomMycustom mycustom : customMycustoms) {
                    LocalDateTime createTime = mycustom.getEntryCustomerTime();
                    String date = createTime.format(ofPattern);
                    if (map.containsKey(date)) {
                        Integer count = map.get(date);
                        map.put(date, count + 1);
                    }
                }
            }
            for (String key : map.keySet()) {
                Integer value = map.get(key);
                counts.add(value);
            }
            maps.put("count", counts);
        } else if ("month".equals(type)) {
            List<Integer> counts = new ArrayList<>();
            List<String> nowMonthDay = TimeUtil.getNowMonthDay();
            maps.put("subscript", nowMonthDay);
            LinkedHashMap<String, Integer> map = new LinkedHashMap<>();

            for (String monthDay : nowMonthDay) {
                map.put(monthDay, 0);
            }
            LocalDate currentDate = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM");
            String currentYearMonth = currentDate.format(formatter);
            List<CustomMycustom> customMycustoms = customMycustomMapper.getCustomDataByNowMonth(currentYearMonth);
            if (!ObjectUtils.isEmpty(customMycustoms)) {
                DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                for (CustomMycustom customMycustom : customMycustoms) {
                    LocalDateTime createTime = customMycustom.getEntryCustomerTime();
                    String date = createTime.format(ofPattern);
                    if (map.containsKey(date)) {
                        Integer count = map.get(date);
                        map.put(date, count + 1);
                    }
                }
            }
            for (String key : map.keySet()) {
                Integer value = map.get(key);
                counts.add(value);
            }
            maps.put("count", counts);
        } else if ("week".equals(type)) {
            List<Integer> counts = new ArrayList<>();
            List<String> nowWeekDay = TimeUtil.getNowWeekDay();
            maps.put("subscript", nowWeekDay);
            LinkedHashMap<String, Integer> map = new LinkedHashMap<>();

            for (String weekDay : nowWeekDay) {
                map.put(weekDay, 0);
            }
            List<CustomMycustom> customMycustoms = customMycustomMapper.getCustomDataByNowWeek();
            if (!ObjectUtils.isEmpty(customMycustoms)) {
                DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                for (CustomMycustom customMycustom : customMycustoms) {
                    LocalDateTime createTime = customMycustom.getEntryCustomerTime();
                    String date = createTime.format(ofPattern);
                    if (map.containsKey(date)) {
                        Integer count = map.get(date);
                        map.put(date, count + 1);
                    }
                }
            }
            for (String key : map.keySet()) {
                Integer value = map.get(key);
                counts.add(value);
            }
            maps.put("count", counts);
        }
        return maps;
    }

    @Override
    public void top(Integer id) {
        Integer top=1;
       customMycustomMapper.topOrDown(id,top);
    }
     @Override
    public void down(Integer id) {
        Integer top=0;
       customMycustomMapper.topOrDown(id,top);
    }
 @Override
    public void personalTop(Integer id) {
        Integer top=1;
       customMycustomMapper.personalTopOrDown(id,top);
    }
     @Override
    public void personalDown(Integer id) {
        Integer top=0;
       customMycustomMapper.personalTopOrDown(id,top);
    }


}